package com.study.webapp.leetcode;


/**
 * 两字符串相乘
 */
public class Leet_43 {

    public static void main(String[] args) {
        System.out.println(multiply("26","39"));
    }


    public static String multiply(String num1, String num2) {
        String ans = "0";
        if (ans.equals(num1) || ans.equals(num2)) {
            return ans;
        }
        int m = num1.length() - 1, n = num2.length() - 1;
        for (int i = n; i>=0; i--) {
            StringBuffer buffer = new StringBuffer();
            int add = 0;
            for (int j = n; j > i; j -- ) {
                buffer.append(0);
            }
            int x = num2.charAt(i) - '0';
            for (int j = m; j>= 0; j--) {
                int y = num1.charAt(j) - '0';
                int result = x * y + add;
                buffer.append(result % 10);
                add = result / 10;
            }
            if (add != 0) {
                buffer.append(add % 10);
            }
            ans = addString(ans,buffer.reverse().toString());
        }
        return ans;
    }

    private static String addString(String num1, String num2) {
        int i = num1.length() - 1, j = num2.length() - 1, add = 0;
        StringBuffer buffer = new StringBuffer();
        while (i >= 0 || j >= 0 || add != 0) {
            int x = i >= 0 ? num1.charAt(i) - '0': 0;
            int y = j >= 0 ? num2.charAt(j) -'0' : 0;
            int result = x + y + add;
            buffer.append(result % 10);
            add = result /10;
            i--;
            j--;
        }
        return buffer.reverse().toString();
    }


}
